package com.ljtxxhwj.myblob.controller;

import com.ljtxxhwj.myblob.entity.Draft;
import com.ljtxxhwj.myblob.service.DraftService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/draft")
public class DraftController {
    @Autowired
    DraftService draftService;

    private String pathString = "/home/ljt/Desktop/md/draft/";


    @GetMapping("/list.do")
    public List<Draft> list(@RequestParam("userId") int userId){
        return draftService.list(userId);
    }

    @GetMapping("/delete.do")
    public String delete(@RequestParam("draftId") int draftId){
        System.out.println("draftId = " + draftId);
        Draft draft = draftService.get(draftId);
        draftService.delete(draftId);

        String draftContent = draft.getDraftContent();
        String filePath = pathString + draftContent;
        File file = new File(filePath);
        file.delete();
        return "{ delete : success }";
    }

    @PostMapping("/save.do")
    public String save(@RequestBody Draft draft){
        System.out.println("draft = " + draft);
        Integer userId = draft.getUser().getUserId();
        Timestamp draftDate = new Timestamp(new Date().getTime());

        String filePath = userId + "_" + draftDate.getTime() + ".md";
        try (OutputStream output = new FileOutputStream(pathString+filePath)) {
            IOUtils.write(draft.getDraftContent(), output);
        } catch (IOException e) {
            e.printStackTrace();
        }

        draft.setDraftContent(filePath);
        draft.setDraftDate(draftDate);
        draftService.save(draft);
        return "{ save : success }";
    }

    @PostMapping("/update.do")
    public String update(@RequestBody Draft draft){
        System.out.println("draft = " + draft);
        Integer userId = draft.getUser().getUserId();
        Timestamp draftDate = new Timestamp(new Date().getTime());

        String filePath = userId + "_" + draftDate.getTime() + ".md";
        try (OutputStream output = new FileOutputStream(pathString+filePath)) {
            IOUtils.write(draft.getDraftContent(), output);
        } catch (IOException e) {
            e.printStackTrace();
        }

        draft.setDraftContent(filePath);
        draft.setDraftDate(draftDate);
        draftService.update(draft);
        return "{ update : success }";
    }
}
